package com.hzdp.netty.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

public class UdpServer {

	public void run(int port) throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
					.handler(new SimpleChannelInboundHandler<DatagramPacket>() {
						@Override
						protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
							String req = msg.content().toString(CharsetUtil.UTF_8);
							ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("Received:" + req, CharsetUtil.UTF_8), msg.sender()));
						}

						@Override
						public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
							ctx.close();
							cause.printStackTrace();
						}
					});
			b.bind(port).sync().channel().closeFuture().await();
		} finally {
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		new UdpServer().run(8080);
	}
}
